import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

import '../constant/sp_key.dart';
import '../util/sputil.dart';
import '../util/string_util.dart';
import 'mqtt_manager.dart';

class MqttSingleton {
  static final MqttSingleton _singleton = MqttSingleton._internal();
  static const String secKey = "iWith!@#xiaodaren";
  final String serverUri = 'api-test.iwith-smart.com'; // MQTT服务器地址 测试地址
  final String clientId = SPUtil.instance.get(SPKey.sn)??""; // 客户端ID
  final int port = 8883; // MQTT服务器端口 测试端口号
  late MqttServerClient _client;

  factory MqttSingleton() {
    return _singleton;
  }

  MqttSingleton._internal() {
    _client = MqttServerClient(serverUri, clientId);
    _client.port = port;
    _client.logging(on: true); // 开启日志
    _client.keepAlivePeriod = 60; // 设置心跳为一分钟
    _client.autoReconnect = true; // 开启自动重连
    _client.onAutoReconnect = _onAutoReconnect; // 设置自动重连回调
    _client.onConnected = _onConnected; // 设置连接成功回调
    _client.onDisconnected = _onDisconnected; // 设置断开连接回调
    _client.resubscribeOnAutoReconnect = true; // 自动重连后重新订阅主题
    _client.setProtocolV311();
  }

  void _onAutoReconnect() {
    // 断线重连时的处理逻辑
    print('MqttSingleton--- Attempting to reconnect...');
  }

  void _onConnected() {
    // 连接成功时的处理逻辑
    print('MqttSingleton--- Connected to the MQTT server');
    _client.subscribe(_mqttTopic(), MqttQos.atLeastOnce);
    //收到MQTT消息
    _client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage mqttMessage = c[0].payload as MqttPublishMessage;
      final String topic = c[0].topic;
      var message = const Utf8Decoder().convert(mqttMessage.payload.message);
      print("MqttSingleton--- 收到主题--$topic--的message: $message");
      // 在这里可以添加对消息的处理逻辑，比如解析消息内容并作出相应的响应
      MqttManager.receiveMsg(message);
    });
  }

  String _mqttTopic() {
    String topic = "p2p/100002/com.aiwer.aiwertvapp/1-${SPUtil.instance.get(SPKey.uid) ?? ""}";
    print('MqttSingleton--- 订阅主题$topic');
    return topic;
  }

  void _onDisconnected() {
    // 断开连接时的处理逻辑
    print('MqttSingleton--- Disconnected from the MQTT server');
  }

  //开发环境连接
  void connect() async {
    //未登录不连接。
    if (!(SPUtil.instance.get(SPKey.isLogin) ?? false)) {
      print('MqttSingleton--------未登录，不连接mqtt-----');
      return;
    }
    print('MqttSingleton--------开始连接mqtt-----');
    String username = StringUtil.currentTimestempMS();
    String password = StringUtil.calculateMD5(username + secKey);
    try {
      if (kReleaseMode) {
        //SSL加密连接
        SecurityContext securityContext = SecurityContext.defaultContext;
        // 加载证书
        // ByteData fileData = await rootBundle.load('assets/certificate.pem');
        // securityContext.setTrustedCertificatesBytes(fileData.buffer.asUint8List());
        _client.securityContext = securityContext;
        _client.secure = true;
        var status = await _client.connect(username, password).then((value) {
          print('MqttSingleton---连接结果---$value');
        });
      } else {
        print('MqttSingleton---非SSL连接--');
        await _client.connect(username, password).then((value) {
          print('MqttSingleton---连接结果---$value');
        });
      }
    } on Exception catch (e) {
      print('MqttSingleton---Exception during connection: $e');
      _client.disconnect();
    }
  }

  void disconnect() {
    if (_client.connectionStatus?.state == MqttConnectionState.connected) {
      _client.disconnect();
    }
  }
}
